package com.spring.cardapi.web.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.spera.genutil.TokenUtil;
import com.spring.cardapi.web.dao.CardApiMapper;
import com.spring.cardapi.web.model.Consume;
import com.spring.cardapi.web.model.MyCoupon;
import com.spring.cardapi.web.model.Order;
import com.spring.cardapi.web.model.PointBill;
import com.spring.cardapi.web.service.CardApiService;
import com.spring.common.web.dao.ContractsMapper;
import com.spring.common.web.dao.CrmContactMapper;
import com.spring.common.web.model.TracelogboWithBLOBs;
import com.spring.rechargeapi.web.service.RechargeApiService;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.iputil.HttpClientUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.sso.api.web.dao.FamilyMemberMapper;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.dao.SsoTracelogboMapper;
import com.sso.api.web.model.FamilyMember;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoUser;
@Service
public class CardApiServiceImpl implements CardApiService{
	@Resource
	private CardApiMapper cardApiMapper;
	
	@Resource
	private SsoMapper ssoMapper;
	
	@Resource
	private FamilyMemberMapper familyMemberMapper;
	
    @Resource
    private JedisCache jedisCache;
   
    @Resource
    private RechargeApiService rechargeApiService;
    
	@Resource
	private ContractsMapper contractsMapper;	
	
	@Resource
	private CrmContactMapper crmContractsMapper;
	
	@Resource
	private SsoTracelogboMapper ssoTracelogboMapper;
	
    /**
	 * 查看自己消费记录
	 */
    @Override
	public Map<String, Object> getOrderList(String token, String orderID, String rechargecardID, 
			String membercardID, String page_size, String page_index, String skip, String rows)  throws Exception{
		
			// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap<String, Object>();

			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}
			
			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			if(rechargecardID!=null&&rechargecardID.equals("")){
				rechargecardID=null;
			}
			if(membercardID!=null&&membercardID.equals("")){
				membercardID=null;
			}
			if(orderID!=null&&membercardID.equals("")){
				orderID=null;
			}

			HashMap<String, Object> hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);

			
			hm.put("c_user_id", c_user_id);
			hm.put("orderID", orderID);
			hm.put("rechargecardID", rechargecardID);
			hm.put("membercardID", membercardID);

			
			List<Order> list = cardApiMapper.getOrderList(hm);
					

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
			m.put(ApplicationUtils.DATASET, list);

			return m;
		
	}
    
    
	/**
	 * 查看自己消费记录
	 */
	@Override
	public Map<String, Object> getConsumeList(String token,String card_id,String page_size,
			String page_index,String skip,String rows)  throws Exception{
		
			// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();

			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}
			
//			String c_user_id = jedisCache.lindex(token, 0);
			
			HashMap hmc=MyTools.checkIsNotNull(card_id);
			if(hmc!=null){
				return hmc;
			}
			
			
			HashMap hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
			
			hm.put("card_id", card_id);
			
			List<Consume> list = cardApiMapper.getConsumeList(hm);
					

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
			m.put(ApplicationUtils.DATASET, list);

			return m;
		
	}
	/**
	 * 查看自己积分流水记录
	 */
	@Override
	public Map<String, Object> getPointBillList(String token,String page_size,
			String page_index,String skip,String rows) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		String c_family_id = jedisCache.hget(token, TokenUtil.FAMILY_ID);
		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		hm.put("c_family_id", c_family_id);
		
		
		List<PointBill> list = cardApiMapper.getPointBillList(hm);
				

		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		m.put(ApplicationUtils.DATASET, list);

		return m;
	}
	
	/**
	 * 产生优惠码
	 */
	public Boolean b=false;
	
	@Override
	public Map<String, Object> createCouponCode(String token) throws Exception{
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		b=false;
		gcode=0;
		
		while (!b){
			b=insertCoupon(c_user_id);
			
		}
		
		HashMap hm=new HashMap();
		hm.put("coupon_code", gcode);
		List list=new ArrayList();
		list.add(hm);
		
		
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		
		
		return m;
	}
	int gcode=0;
	//插入优惠表
	public Boolean  insertCoupon(String c_user_id){
		Boolean status=false;
		
		int code=(int)(Math.random()*90000000+10000000);
		
		System.out.println(code);
		
		try{
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("code", code);
		int effect = cardApiMapper.createCouponCode(hm);
		if(effect!=1){
			status=false;
		}
		
		
		}catch(Exception ex){
			status=false;
		}
		
		status=true;
		gcode=code;
		return status;
	}
	
	
	
	/**
	 * 查看自己的优惠码
	 */
	@Override
	public Map<String, Object> getMyCouponList(String token,String isused) throws Exception{
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		

		
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("isused", isused);
		
		List<MyCoupon> list = cardApiMapper.getMyCouponList(hm);
		
		
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		m.put(ApplicationUtils.DATASET, list);
		
		return m;
	}
	
	
	//修改积分
	@Override
	public Map<String, Object> updatePoint(String c_user_id,String point_source_code,String change_point,
			String change_type_code,String desc) throws Exception{
		Map<String, Object> m = new HashMap();

		
		HashMap<String,Object> hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("point_source_code", point_source_code);
		hm.put("change_point", change_point);
		hm.put("change_type_code", change_type_code);
		hm.put("desc", desc);
		
		HashMap userhm=ssoMapper.selectUserByID(hm);
		String c_family_id=String.valueOf(userhm.get("c_family_id"));
		
		hm.put("c_family_id", c_family_id);

		int effect= ssoMapper.updatePointReamin(hm);
		if(effect!=1){
			throw new Exception();			
		}
		BigDecimal remain_point=ssoMapper.selectReaminPoint(hm);
		
		hm.put("remain_point", remain_point);
		
		int effect2=cardApiMapper.insertPointJournal(hm);
		if(effect2!=1){
			throw new Exception();
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");

		
		return m;
	}

	@Override
	public Map<String, Object> addUser(RequestUser user,HttpServletRequest request) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();

		//更新用户
		if(user.getC_user_id()!=null){
			if(user.getIsToDelete()==1){
				user.setEntityAvailableState(20);
			}			
			String newPhone=user.getPhone();
			//判断是否修改业务数据库手机号
				HashMap<String,Object> param=new HashMap<String,Object>();        	
	        	param.put("c_user_id", user.getC_user_id());
	        	param.put("newPhone", newPhone);
	    		
	        	updatePhone(user.getC_user_id(),newPhone);
	        	
			
			int effect=ssoMapper.updateUser(user);
			
			if(effect<1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "更新失败");
				return m;
			}else{
				TracelogboWithBLOBs traclelogba = MyTools.getOaLogByRequest(request);
				traclelogba.setEntitytypename("c_family_member");
				traclelogba.setEntityid(user.getC_user_id());
				traclelogba.setLogcategory(2);
				traclelogba.setLogdescription(MyTools.getChangeByObject(user, "修改"));
				int effect3=ssoTracelogboMapper.insert(traclelogba);
				System.out.println(effect3);	
				
				
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "更新成功");
				return m;
			}
			
		}else{
			
		if(user.getUserName()==null){
			user.setUserName(ApplicationUtils.randomUUID());
		}		
		if(user.getC_role_id()!=null){
		if(user.getC_role_id().equals("1")){
			user.setSex_code("1");
		}
		if(user.getC_role_id().equals("2")){
			user.setSex_code("2");
		}
		}
		
		HashMap<String,Object> family=new HashMap<String,Object> ();
		
		family.put("family_name", user.getPhone()+"用户家庭");
		family.put("wx_point", 0);
		String c_familyID=ApplicationUtils.randomUUID();
		family.put("id", c_familyID);
		
		family.put("phone", user.getPhone());
		family.put("address", user.getAddress());
		family.put("zipcode", user.getZipcode());
		family.put("family_phone", user.getFamily_phone());		

		
		if(user.getC_user_id()==null){
			String c_user_id=ApplicationUtils.randomUUID();
			user.setC_user_id(c_user_id);
		}

		if(user.getPhone()!=null){
			HashMap<String, Object> h1=new HashMap<String, Object>();
			h1.put("phone", user.getPhone());
			int count=ssoMapper.getUserCountByPhone(h1);
			if(count>0){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "手机号重复");
				return m;
			}
		}
			if(user.getC_family_id()==null){
				
				int effect=ssoMapper.insertFamily(family);
				if(effect!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "插入家庭失败");
					throw new Exception();
				}
				TracelogboWithBLOBs traclelogba = MyTools.getOaLogByRequest(request);
				traclelogba.setEntitytypename("c_family");
				traclelogba.setEntityid(c_familyID);
				traclelogba.setLogcategory(1);
				traclelogba.setLogdescription(MyTools.getChangeByMap(family, "新增"));
				int effect3=ssoTracelogboMapper.insert(traclelogba);
				System.out.println(effect3);
				
		}
			//如果没有家庭号生成家庭号然后设置新家庭号
			if(user.getC_family_id()==null){
				user.setC_family_id(c_familyID);
			}
			
			
			int effect2=ssoMapper.insertUser(user);
			if(effect2!=1){
				throw new Exception();
			}	
			
			TracelogboWithBLOBs traclelogba = MyTools.getOaLogByRequest(request);
			traclelogba.setEntitytypename("c_family_member");
			traclelogba.setEntityid(user.getC_user_id());
			traclelogba.setLogcategory(1);
			traclelogba.setLogdescription(MyTools.getChangeByObject(user, "新增"));
			int effect3=ssoTracelogboMapper.insert(traclelogba);
			System.out.println(effect3);	
			
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("c_familyID", c_familyID);
		hm.put("c_user_id",user.getC_user_id() );		
		
		m.put(ApplicationUtils.DATASET, hm);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		}

		return m;
	}
	
	//type 1:会员卡，2充值卡
	@Override
	public Map<String, Object> insertFile(String fileList,String contractID) throws Exception{	
		Map<String, Object> m = new HashMap<String, Object>();
		
		JSONArray json = JSONArray.fromObject(fileList);

		// 
		for (int i = 0; i < json.size(); i++) {
			JSONObject jsonObject = json.getJSONObject(i);
			String url = String.valueOf(jsonObject.get("url")) ;
			String osskey = String.valueOf(jsonObject.get("osskey")) ;
			String file_size = String.valueOf(jsonObject.get("file_size")) ;
			String file_name = String.valueOf(jsonObject.get("file_name")) ;
			String file_type = String.valueOf(jsonObject.get("file_type")) ;
			
			HashMap hm=new HashMap();
			hm.put("url", url);
			hm.put("osskey", osskey);
			hm.put("file_size", file_size);
			hm.put("file_name", file_name);
			hm.put("file_type", file_type);
			
			String fileID=ApplicationUtils.randomUUID();
			
			hm.put("fileID", fileID);		
			hm.put("contractID", contractID);
			
			int effect=cardApiMapper.insertFile(hm);
			
			int effect2=cardApiMapper.insertContractFile(hm);
			
			if(effect<1||effect2<1){
				throw new Exception();
			}
		
		}

		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");


		return m;
	}
	
	@Override
	public Map<String, Object> insertContract(HashMap hm) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();
		
		//HashMap<String, Object> h1=new HashMap<String, Object>();
/*		String contractID=MyTools.ObjectToString(hm.get("contractID"));
		if(contractID==null){
			
		}*/
		
		String contractID=ApplicationUtils.randomUUID();
		hm.put("contractID", contractID);
		
		String kids_parkID=MyTools.ObjectToString(hm.get("kids_parkID"));
		
		String kids_name=cardApiMapper.getKidParkNameByID(kids_parkID);				
		
		hm.put("partB", kids_name);
		
		int effect=cardApiMapper.insertContract(hm);

		HashMap<String, Object> r1=new HashMap<String, Object>();
		r1.put("contractID", contractID);
		if(effect<1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "插入失败");
		}else{
			m.put(ApplicationUtils.DATASET,r1);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "插入成功");
			
		}

		return m;
		
	}
	
//	@Override
//	public Map<String, Object> updateUserAddCard(SsoUser ssoUser,) throws Exception{
//		Map<String, Object> m = new HashMap<String, Object>();
//		
//		//HashMap<String, Object> h1=new HashMap<String, Object>();
//		
//		
//		
//		String MemberNumber=ssoUser.getMember_number(String );//  ssoMapper.getMemberByID(hm2);
//		
//		//修改用户表
//		
//		HashMap<String ,Object> hm2=new HashMap<String ,Object>();
//		hm2.put("c_user_id", c_user_id);
//		hm2.put("kids_park_id", kids_parkID);
//		
//		if(MemberNumber==null||MemberNumber.equals("")){
//			String count4=ssoMapper.getMemberCount(afterPayPara);
//			
//			String sso_member_number=areaCode+index+year+count4;
//			
//			hm2.put("member_number", sso_member_number);
//			hm2.put("card_number", card_number);
//			hm2.put("card_out_number", card_out_number);
//			hm2.put("member_type", "1");
//			
//			int effect=ssoMapper.updateUserNumber(hm2);
//				
//			if(effect<1){
//				throw new Exception();
//			}
//		}
//			m.put(ApplicationUtils.DATASET,r1);
//			m.put(ApplicationUtils.STATUS, "1");
//			m.put(ApplicationUtils.MSG, "插入成功");
//			
//		
//
//		return m;
//		
//	}
	
	
/*	@Override
	public Map<String, Object> createStaffCard(String user_id,String kids_park_id,String name, String phone, String email, String desc, String identity_card)  throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

			HashMap hmc=MyTools.checkIsNotNull(name,phone,kids_park_id);
			if(hmc!=null){
				return hmc;
			}

			RequestUser ru=new RequestUser();
			ru.setPhone(phone);
			ru.setReal_name(name);
			ru.setEmail(email);
			ru.setIdentity_card(identity_card);
			ru.setMember_name(name);
			
			//注册用户
			Map<String, Object> hm=this.addUser(ru);
			
			if(!hm.get(ApplicationUtils.STATUS).equals("1")){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, hm.get(ApplicationUtils.MSG));
				return m;
			}
			
			HashMap<String,Object> hmr=(HashMap<String,Object>)hm.get(ApplicationUtils.DATASET);
			String c_family_id=MyTools.ObjectToString(hmr.get("c_familyID"));
			String c_user_id=MyTools.ObjectToString(hmr.get("c_user_id"));
			
//			HashMap<String,Object> hmr
//			rechargeApiService.insertRechargecard();
			
		return m;
	}*/
	
	@Override
	public Map<String, Object> createMemberNumber(String kids_park_id,String cardType,String MemberType)  throws Exception{
		
		
//		hm.put("c_familyID", c_familyID);
//		hm.put("c_user_id",user.getC_user_id() );		
//		
//		m.put(ApplicationUtils.DATASET, hm);
//		
//		
//		//生成会员码
//		HashMap KidsAndRegion=memberCardApiMapper.getKidsAndRegion(afterPayPara);
//		String index=String.valueOf(KidsAndRegion.get("index"));
//		String areaCode=String.valueOf(KidsAndRegion.get("areaCode"));
//		
//		afterPayPara.put("index", index);
//		afterPayPara.put("areaCode", areaCode);
//		
//		String count=rechargeApiMapper.getRechargeCount(afterPayPara);			
//		if(index.length()==1){
//			index="0"+index;
//		};			
//		
//		Date d=new Date();
//		SimpleDateFormat sFormat = new SimpleDateFormat("yy");
//		String year=sFormat.format(d);
//		
//		String recharge_number=areaCode+index+"2"+year+count;
//		
		
		return null;
	}

	public BaseResult updatePhone(String cUserID,String newPhone) throws Exception{
		HashMap<String,Object> param=new HashMap<String,Object>();
		param.put("cUserID", cUserID);
		param.put("newPhone", newPhone);
		
		int effect = contractsMapper.updatePhone(param);			
		//MyTools.checkEffect(effect);			
		int effect2 = crmContractsMapper.updatePhone(param);
		//MyTools.checkEffect(effect2);	
		
		return new BaseResult();
	};
	
}
